package com.kylin.artwork.openapi.starter.interceptor;

import com.kylin.shared.common.consts.Constants;
import com.kylin.shared.utils.ApplicationUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * traceId拦截生成器
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年06月18日 20:58
 */
public class TraceIdInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        String traceId = request.getHeader(Constants.HTTP_TRACE_ID_HEADER);
        if (StringUtils.isEmpty(traceId)) {
            traceId = ApplicationUtils.randomUUID();
        }
        MDC.put(Constants.LOG_TRACE_ID, traceId);
        response.setHeader(Constants.HTTP_TRACE_ID_HEADER, traceId);
        return true;
    }
}
